import type { NextApiRequest, NextApiResponse } from "next";
import os from "os";
import path from "path";
import { createReadStream } from "fs";
import FormData from "form-data";
import axios from "axios";
import { SERVERURL } from "@/pages/api/config";

interface Data {
  message: string;
}

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  let imageName: string | string[] | undefined = req.query.imageSrc;
  console.log(imageName);
  let homePath: string = os.userInfo().homedir;
  let outputPath: string = path.join(
    homePath,
    "stable-diffusion-webui/outputs/txt2img-images/"
  );
  let imagePath: string = path.join(outputPath, imageName as string);
  console.log(imagePath);
  let formData: FormData = new FormData();
  let imgFile = createReadStream(imagePath);
  formData.append("file", imgFile);
  let len: number = await new Promise((resolve, reject) => {
    return formData.getLength((err, length) =>
      err ? reject(err) : resolve(length)
    );
  });
  const targetUploadURL: string = `${SERVERURL}novalai/upload_from_server/`;
  console.log(`send a picture to ${targetUploadURL} ...`);
  axios({
    url: targetUploadURL,
    method: "post",
    params: {
      type: "image",
    },
    data: formData,
    headers: {
      ...formData.getHeaders(),
      "Content-Length": len,
    },
  }).then((res) => {
    console.log(res.data);
  });

  res.status(200).json({ message: "successful" });
}
